<?php


class Perm {
    protected $objUser;


    public function IsAuthenticated($Redirect=false) {
        if ( !isset( $_SESSION["User"]["Id"]) ) {
            if ($Redirect == true) {
                QApplication::Redirect( __APPS_WWW__ . "/login.php");
            }
            return false;
        }
        else
            return true;

    }

    public function GetUserId() {
        if ( isset( $_SESSION["User"]["Id"] )) {
            return $_SESSION["User"]["Id"];
        }
        return false;
    }

    public function Check_Password ( $UserName, $Password ) {
        $Password = $this->md5crypt($Password);

        $this->objUser = User::LoadArrayByUserNamePassword($UserName,$Password);
        if ($this->objUser == NULL) {
//echo "Debug User or password";
            return false;
        }
        return true;
    }




    public function Authenticate( $UserName, $Password ) {
//set session to 1 min
        ini_set('session.gc_maxlifetime', 1);

        $Password = $this->md5crypt($Password);
        $this->objUser = User::LoadArrayByUserNamePassword($UserName,$Password);
        if ($this->objUser == NULL) {
//echo "Debug User or password";
            return false;
        }
//If user active
        if ($this->objUser[0]->Active == false  ) {
//echo "Debug User is not active";
            return false;
        }

        $_SESSION[_SV_PERM_][_SV_PERM_PRole_]     = $this->objUser[0]->PrimaryRole;
//if role not active
        if ( !$this->objUser[0]->PrimaryRole->Active == true ) {
//echo "Debugprole is not active";
            return false;
        }

        $_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_]= false;
        $_SESSION[_SV_PERM_][_SV_PERM_Obj_]       = $this->objUser[0];
        $_SESSION[_SV_PERM_][_SV_PERM_ID_]        = $this->objUser[0]->Id ;
        $_SESSION[_SV_PERM_][_SV_PERM_USERNAME_]  = $this->objUser[0]->UserName;
        $_SESSION[_SV_PERM_][_SV_EUSERID_]        = $this->objUser[0]->Id ;


//Check if has the role of admin
        if ( $_SESSION[_SV_PERM_][_SV_PERM_PRole_]->Id == 1)
            $_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_]= true;

        $_SESSION[_SV_PERM_][_SV_PERM_ERole_]     = $this->objUser[0]->GetRoleAsEffectiveArray();

//Check if efficteve role as admin
        foreach ( $_SESSION[_SV_PERM_][_SV_PERM_ERole_] as $Role)
            if ( $Role->Id == 1) $_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_]= true;

        $dttTime = new QDateTime();
        $dttTime->setDate (date("Y"), date("m"), date("d"));
        $dttTime->setTime (date("H"), date("i"), date("s"));

//Write Last login
        $this->objUser[0]->LastLogin = $dttTime;
//Write Ip
        $ip = $_SERVER['REMOTE_ADDR'];
//$this->objUser[0]->LastIp = $ip;
        $this->objUser[0]->Save();


        return true;
    }

    public function SetEUserId($EuserID) {
//Check if Euser is in THe list beffore assign

//$_SESSION[_SV_PERM_][_EUSER_]

    }



    Public function LogOut() {
        session_destroy();
    }


    public function md5crypt($password) {
// create a salt that ensures crypt creates an md5 hash
        $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                .'abcdefghijklmnopqrstuvwxyz0123456789+/';
        $salt='$1$';
        for($i=0;
        $i<9;
        $i++) {
            $salt.=$base64_alphabet[rand(0,63)];
        }
// return the crypt md5 password
        return crypt($password,$salt.'$');
    }

    public function GetEusers() {
        if  (! $this->IsAuthenticated(false) ) {
            return false;
        }
        else {
            $User = $_SESSION[_SV_PERM_][_SV_PERM_Obj_] ;
            return $User->GetRoleAsEffectiveArray();
        }

    }

//Check Perm
    public function IsAdmin($Redirect=false) {
//first check if authenticated
        if ( $this->IsAuthenticated(true) ) {
            if ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_])
                return true;
            else {
//not admin
                if ( $Redirect == true) {
                    $this->Redirect(404);
                }
                else
                    return false;
            }
        }

    }
    public function IsManager($Redirect=false) {
//first check if authenticated
        if ( $this->IsAuthenticated(true) ) {
            if ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_])
                return true;
//CHANGE TO CHECK IF MANAGER
            elseif ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_])
                return true;
            else {
//not admin
                if ( $Redirect == true) {
                    $this->Redirect(404);
                }
                else
                    return false;
            }
        }
    }

    public function Check_Org_Perm($OrgId, $Redirect=true) {
//Admin
        if ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_])
            return true;
        $Access = Org::CheckOrgPerm($OrgId);
        if (empty ($Access)) {
            header($_SERVER['SERVER_PROTOCOL'] . ' 401 Access Denied');
            header('Status: 401 Access Denied', true);
            if ( $Redirect == true) {
                $this->Redirect(404);
            }
            else
                return false;
        }
        else
            return true;
    }

    public function Check_Person_Perm($PersonId, $Redirect=true) {
//Admin
        if ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_])
            return true;
        $Access = Person::CheckPersonPerm($PersonId);
        if (empty ($Access)) {
            header($_SERVER['SERVER_PROTOCOL'] . ' 401 Access Denied');
            header('Status: 401 Access Denied', true);
            if ( $Redirect == true) {
                $this->Redirect(404);
            }
            else
                return false;
        }
        else
            return true;
    }

//AUTO COMPELTE LIST
    public function AutoList_MySchoolList($strParameter,$Return_Type) {
        if ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_]) {
            return Org::AutoListAllSchoolList($strParameter,$Return_Type);
        }
        else
            return Org::AutoListMySchoolList($strParameter,$Return_Type);
    }
    public function AutoList_MyOrgList($strParameter,$Return_Type) {
        if ($_SESSION[_SV_PERM_][_SV_PERM_Admin_Role_]) {
            return Org::AutoListAllOrgList($strParameter,$Return_Type);
        }
        else
            return Org::AutoListMyOrgList($strParameter,$Return_Type);
    }



    private function Redirect($ErrorNum=null,$page=null) {
        if ($ErrorNum) {
            switch ($ErrorNum) {
                case 404:
                    echo "Access Denided to this Resource.";
                    exit;
                    break;
                case 409:
                    echo "i equals 1";
                    break;
            }
        }
    }

    public function Redirect2Index() {
        QApplication::Redirect(__APPS_WWW__);
    }

    public function Translate($Name,$Id) {
        switch ($Name) {
            Case "User":
                return User::Load($Id)->PrimaryRole;
                break;
            case "Role":
                $Role = Role::Load($Id);
                $User = $Role->GetUserAsPrimaryArray();
                if ( isset($User[0]) )
                    return $User[0];
                else
                    return false;

                break;
            default:
                echo "Error in Switch translate";
                exit;

        }
    }


    public function HeaderPrint() {
        if (isset($_SESSION[_SV_PERM_][_SV_PERM_Obj_]->Person->FirstName) )
            $Person = $_SESSION[_SV_PERM_][_SV_PERM_Obj_]->Person->FirstName;
        else if (isset(  $_SESSION[_SV_PERM_][_SV_PERM_USERNAME_]) )
            $Person =  $_SESSION[_SV_PERM_][_SV_PERM_USERNAME_];
          
        $UserHtml = "<div id=\"willOpen\"><span class=\"headerSmall\">Welcome, ";
        if ( $this->IsAuthenticated(false) == false) {
            echo "<div id=\"viewSource\"><a href='" . __APPS_WWW__ .  "/login.php'" . ">Login</a></div>";
            echo $UserHtml . "Guest" . "</span></div>";
        }
        else {
            echo "<div id=\"viewSource\"><a href='" . __APPS_WWW__ .  "/logout.php'" . ">Logout</a></div>";
            echo $UserHtml . $Person .  "</span></div>";

        }
    }


}

/*
DENIED	0
CR	3	0011
CRU	7	0111
CRD	11	1011
CRUD	15	1111
R	2	0010
RU	6	0110
RUD	14	1110
RD	10	1010

*/
?>
